package com.micro.ai.models.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.models.entity.ModelType;
import com.micro.ai.models.mapper.ModelTypeMapper;
import com.micro.ai.models.service.ModelTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 模型类型服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class ModelTypeServiceImpl extends ServiceImpl<ModelTypeMapper, ModelType> implements ModelTypeService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelType create(ModelType modelType) {
        if (modelType == null) {
            throw new BusinessException("M0000", "模型类型信息不能为空");
        }
        
        LambdaQueryWrapper<ModelType> query = new LambdaQueryWrapper<>();
        query.eq(ModelType::getTenantId, modelType.getTenantId())
             .eq(ModelType::getTypeCode, modelType.getTypeCode());
        
        ModelType existing = this.getOne(query);
        if (existing != null) {
            throw new BusinessException("M0001", "类型代码已存在: " + modelType.getTypeCode());
        }
        
        LocalDateTime now = LocalDateTime.now();
        modelType.setCreatedAt(now);
        modelType.setUpdatedAt(now);
        
        boolean success = this.save(modelType);
        if (!success) {
            throw new BusinessException("M0003", "保存模型类型失败");
        }
        
        log.info("创建模型类型成功: typeId={}, typeCode={}, typeName={}", 
                modelType.getId(), modelType.getTypeCode(), modelType.getTypeName());
        
        return modelType;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelType update(String id, ModelType modelType) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "模型类型ID不能为空");
        }
        if (modelType == null) {
            throw new BusinessException("M0000", "模型类型信息不能为空");
        }
        
        ModelType existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("M0002", "模型类型不存在: " + id);
        }
        
        if (!existing.getTypeCode().equals(modelType.getTypeCode())) {
            LambdaQueryWrapper<ModelType> query = new LambdaQueryWrapper<>();
            query.eq(ModelType::getTenantId, modelType.getTenantId())
                 .eq(ModelType::getTypeCode, modelType.getTypeCode())
                 .ne(ModelType::getId, id);
            
            ModelType duplicate = this.getOne(query);
            if (duplicate != null) {
                throw new BusinessException("M0001", "类型代码已被其他类型使用: " + modelType.getTypeCode());
            }
        }
        
        modelType.setId(id);
        modelType.setUpdatedAt(LocalDateTime.now());
        
        boolean success = this.updateById(modelType);
        if (!success) {
            throw new BusinessException("M0003", "更新模型类型失败");
        }
        
        log.info("更新模型类型成功: typeId={}, typeCode={}, typeName={}", 
                id, modelType.getTypeCode(), modelType.getTypeName());
        
        return modelType;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "模型类型ID不能为空");
        }
        
        ModelType modelType = this.getById(id);
        if (modelType == null) {
            throw new BusinessException("M0002", "模型类型不存在: " + id);
        }
        
        // 注意：由于外键约束，如果有关联的模型定义，数据库会自动阻止删除
        // 这里可以通过查询给出更友好的提示
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("M0003", "删除模型类型失败");
        }
        
        log.info("删除模型类型成功: typeId={}, typeCode={}", id, modelType.getTypeCode());
    }

    @Override
    public Page<ModelType> pageQuery(int pageNum, int pageSize, String tenantId, String keyword) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<ModelType> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ModelType> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(ModelType::getTenantId, tenantId);
        }
        
        if (StringUtils.hasText(keyword)) {
            query.and(q -> q.like(ModelType::getTypeName, keyword)
                          .or().like(ModelType::getTypeCode, keyword)
                          .or().like(ModelType::getDescription, keyword));
        }
        
        query.orderByAsc(ModelType::getSortOrder).orderByDesc(ModelType::getCreatedAt);
        
        return this.page(page, query);
    }
}

